<?php

namespace JLPay\Utils;

/**
 * 简单的日志工具类
 */
class Logger
{
    private static ?Logger $instance = null;
    private string $logLevel = 'INFO';
    private array $logLevels = [
        'DEBUG' => 0,
        'INFO' => 1,
        'WARNING' => 2,
        'ERROR' => 3
    ];

    private function __construct()
    {
        // 私有构造函数，实现单例模式
    }

    /**
     * 获取Logger实例
     *
     * @return Logger
     */
    public static function getInstance(): Logger
    {
        if (self::$instance === null) {
            self::$instance = new self();
        }
        return self::$instance;
    }

    /**
     * 设置日志级别
     *
     * @param string $level
     */
    public function setLevel(string $level): void
    {
        $this->logLevel = strtoupper($level);
    }

    /**
     * 记录调试日志
     *
     * @param string $message
     * @param array $context
     */
    public function debug(string $message, array $context = []): void
    {
        $this->log('DEBUG', $message, $context);
    }

    /**
     * 记录信息日志
     *
     * @param string $message
     * @param array $context
     */
    public function info(string $message, array $context = []): void
    {
        $this->log('INFO', $message, $context);
    }

    /**
     * 记录警告日志
     *
     * @param string $message
     * @param array $context
     */
    public function warning(string $message, array $context = []): void
    {
        $this->log('WARNING', $message, $context);
    }

    /**
     * 记录错误日志
     *
     * @param string $message
     * @param array $context
     */
    public function error(string $message, array $context = []): void
    {
        $this->log('ERROR', $message, $context);
    }

    /**
     * 记录日志
     *
     * @param string $level
     * @param string $message
     * @param array $context
     */
    private function log(string $level, string $message, array $context = []): void
    {
        if ($this->logLevels[$level] < $this->logLevels[$this->logLevel]) {
            return;
        }

        $timestamp = date('Y-m-d H:i:s');
        $contextStr = empty($context) ? '' : ' ' . json_encode($context, JSON_UNESCAPED_UNICODE);
        
        $logMessage = "[{$timestamp}] [{$level}] {$message}{$contextStr}" . PHP_EOL;
        
        // 输出到标准输出
        echo $logMessage;
        
        // 也可以写入文件
        // file_put_contents('jlpay.log', $logMessage, FILE_APPEND | LOCK_EX);
    }
} 